import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
// 新增导入登录页面组件
import LoginView from '../views/LoginView.vue'
import { useUserStore } from '../stores/user.store.js'
import ApiView from '../views/ApiView.vue'
import RegisterView from '../views/RegisterView.vue'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        {
          path: '/',
          name: 'index',
          component: () => import('../views/pages/IndexPage.vue'),
        },
        {
          path: '/todos',
          name: 'todos',
          component: () => import('../views/pages/TodosPage.vue'),
        },
        {
          path: '/users',
          name: 'users',
          component: () => import('../views/pages/UsersPage.vue'),
        }
      ]
    },
    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('../views/AboutView.vue'),
    // },
    // 新增登录页面路由
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
    },
    {
      path: '/api',
      name: 'api',
      component: ApiView,
    },
  ],
})

router.beforeEach(async (to, from) => {
  const userStore = useUserStore()
  const isAuthenticated = userStore.isLogin
  if (
    // 检查用户是否已登录
    !isAuthenticated &&
    // ❗️ 避免无限重定向
    to.name !== 'login'
  ) {
    // 将用户重定向到登录页面
    return { name: 'login' }
  }
  // if(isAuthenticated && to.name === 'login'){
  //   return { name: 'index' }
  // }
})

export default router
